import { defineStore }       from 'pinia';
import { pathJoin }          from 'src/api/SysApi';
import { getFile, saveFile } from 'src/api/FileApi';
import yaml               from 'js-yaml';
import { useConfigStore } from 'stores/configStore';

export const useYmlStore = defineStore('yml', () =>
{
  //操作
  const getYmlContentByPath = (path: string): Promise<object> =>
  {
    return new Promise((resolve) =>
    {
      getFile(path, false).then((r: string) =>
      {
        resolve(<object>yaml.load(r));
      });
    });
  };
  const getYmlContentByName = (name: string): Promise<object> =>
  {
    return new Promise(async (resolve) =>
    {
      console.log(pathJoin(<string>(await useConfigStore().getConfig())?.configFilePath, 'file', name + '.yml'));
      getFile(pathJoin(<string>(await useConfigStore().getConfig())?.configFilePath, 'file', name + '.yml'), false).then((r: string) =>
      {
        resolve(<object[]>yaml.load(r));
      });
    });
  };
  const saveYmlContentByPath = (path: string, data: object) =>
  {
    return new Promise((resolve) =>
    {
      saveFile(path, yaml.dump(data)).then((r: string) =>
      {
        resolve(r);
      });
    });
  };
  const saveYmlContentByName = (name: string, data: object) =>
  {
    return new Promise(async (resolve) =>
    {
      saveFile(pathJoin(<string>(await useConfigStore().getConfig())?.configFilePath, 'file', name + '.yml'), yaml.dump(data)).then((r: string) =>
      {
        resolve(r);
      });
    });
  };
  return {
    getYmlContentByPath, getYmlContentByName, saveYmlContentByPath, saveYmlContentByName
  };
});
